﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Core.Filters
{

    public class ValidateModelStateFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            // 如果模型状态无效
            if (!context.ModelState.IsValid)
            {
                // 创建一个标准化的错误响应
                var errors = context.ModelState
                    .Where(m => m.Value.Errors.Count > 0)
                    .Select(m => new
                    {
                        Field = m.Key,  // 字段名称
                        Errors = m.Value.Errors.Select(e => e.ErrorMessage).ToList()  // 错误消息
                    }).ToList();

                var responseObj = new
                {
                    Success = false,
                    Message = "模型校验失败",
                    Errors = errors
                };

                // 返回自定义错误响应
                context.Result = new BadRequestObjectResult(responseObj);
            }
        }
    }

}
